package com.msh.frame.web.filter;

import com.msh.frame.client.model.ThreadContext;
import com.msh.frame.web.util.HttpServletRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;


@Slf4j
public class ThreadContextThreadLocalInterceptor implements WebRequestInterceptor {

  private ThreadLocal<ThreadContext> threadLocal;

  public ThreadContextThreadLocalInterceptor(ThreadLocal<ThreadContext> threadLocal) {
    this.threadLocal = threadLocal;
  }

  @Override
  public void preHandle(WebRequest request) {
    ThreadContext threadContext = new ThreadContext();
    Long accountId = HttpServletRequestUtil.getAccountId();
    threadContext.setAccountId(accountId);
    String traceId = HttpServletRequestUtil.getTraceId();
    threadContext.setTraceId(traceId);
    Long tenantId = HttpServletRequestUtil.getTenantId();
    threadContext.setTenantId(tenantId);
    threadLocal.set(threadContext);
  }

  @Override
  public void postHandle(WebRequest request, ModelMap model) {
    threadLocal.remove();
  }

  @Override
  public void afterCompletion(WebRequest request, Exception ex) {
  }
}
